<?php

namespace App\Jobs;

use App\Models\ParkingLot\ChargePlateLog;
use App\Models\ParkingLot\ParkEnterLog;
use App\Models\ParkingLot\ParkingLot;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ChargePlateNotify implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data = $this->data;
        $carNo = \Arr::get($data, 'carNo');
        $parkingLotNo = \Arr::get($data, 'parkingLotNo');
        $parkingLotName = \Arr::get($data, 'parkingLotName');
        $startTime = \Arr::get($data, 'startTime');
        $endTime = \Arr::get($data, 'endTime');
        $duration = intval(\Arr::get($data, 'duration'));
        $appid = \Arr::get($data, 'appid');

        $startTime = Carbon::parse($startTime);
        $endTime = Carbon::parse($endTime);

        if (!ParkingLot::find($parkingLotNo)) {
            \Log::channel('parking')->info('停车充电信息-忽略-车场不存在', $data);
            return;
        }

        if (ChargePlateLog::where(['parking_lot_id' => $parkingLotNo, 'car_no' => $carNo])->where('start_time', $startTime)->exists()) {
            \Log::channel('parking')->info('停车充电信息-忽略-重复记录', $data);
            return;
        }

        $plateLog = ChargePlateLog::create([
            'car_no' => $carNo,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'duration' => $duration,
            'appid' => $appid,
            'parking_lot_name' => $parkingLotName,
            'parking_lot_id' => $parkingLotNo
        ]);

        if ($enterLog = ParkEnterLog::where(['parking_lot_id' => $parkingLotNo, 'car_no' => $carNo])->first()) {
            if (Carbon::parse($enterLog->enter_at) > $startTime) {
                \Log::channel('parking')->info('停车充电信息-有误-车辆入场时间在充电开始之后', $data);
                $plateLog->update(['status' => '车辆不在场']);
                return;
            }
            $plateLog->update(['park_log_id' => $enterLog->id]);
        } else {
            \Log::channel('parking')->info('停车充电信息-有误-车辆不在场', $data);
            $plateLog->update(['status' => '车辆不在场']);
        }

//        $settings = Setting::where('parking_lot_id', $parkingLotNo)->where('category', Setting::CATEGORY_CHARGE_DISCOUNT)->pluck('value', 'key')->toArray();
    }
}
